﻿using System.Collections;
using System.Reflection;

using DevExpress.Data.Filtering;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;

using Kuiper.Core.Providers;

namespace Kuiper.Core;

public class KPSession : Session
{
	private static readonly object _lock = new object();
	private static KPSession? _session;

	public new static KPSession DefaultSession
	{
		get
		{
			lock (_lock)
			{
				return _session ?? (_session = new KPSession());
			}
		}
	}

	public KpMsSQLConnectionProvider? DbConnectionProvider
	{
		get
		{
			if (IsConnected && DataLayer != null)
			{
				return DataLayer as KpMsSQLConnectionProvider;
			}

			return null;
		}
	}

	public KPSession() : base() { }

	protected override void OnBeforeConnect()
	{
		base.OnBeforeConnect();
	}

	protected override void OnAfterConnect()
	{
		base.OnAfterConnect();
	}

	public static void Init()
	{
		DefaultSession.ConnectionString = KpMsSQLConnectionProvider.GetConnectionString("localhost", "DB.Kuiper.MES");
		DefaultSession.AutoCreateOption = AutoCreateOption.DatabaseAndSchema;
	}

	public new static void UpdateSchema(Assembly[] assemblyList)
	{
		XpoDefault.DataLayer = XpoDefault.GetDataLayer(DefaultSession.ConnectionString, AutoCreateOption.DatabaseAndSchema);
		XpoDefault.DataLayer.UpdateSchema(false, XpoDefault.DataLayer.Dictionary.CollectClassInfos(assemblyList));
	}

	public static TObject GetByOID<TObject>(int oid)
	{
		return DefaultSession.FindObject<TObject>(new BinaryOperator("OID", oid));
	}

	public static ICollection GetList(Type targetObjectType, CriteriaOperator filterCriteria = null)
	{
		return DefaultSession.GetObjects(DefaultSession.GetClassInfo(targetObjectType), filterCriteria, null, 0, false, false);
	}

	public static IList<TObject> GetList<TObject>() => new XPQuery<TObject>(DefaultSession).ToList();
}
